package com.atguigu.gmall.common.config.exception.handler;

import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

// aop：通知方法，Controller的异常切面
/**
 * @author lfy
 * @Description
 * @create 2022-12-10 10:53
 */
//controller的异常切面
//@ResponseBody
//@ControllerAdvice  //aop：Advice：通知
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {


    /**
     * 和业务有关的异常；要用 GmallException
     *
     * @param e
     * @return
     */

    @ExceptionHandler(GmallException.class)
    public Result handleGmallException(GmallException e) {
        Result<Object> fail = Result.fail();
        fail.setCode(e.getCode());
        fail.setMessage(e.getMessage());
        return fail;
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        Map<String,String> errMap = new HashMap<>();
        Result<Object> result = Result.fail();
        //1.拿到异常校验的结果
        BindingResult bindingResult = e.getBindingResult();
        //2.吧结果整理后返回给前端{tell:"",consignee:""}
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            String field = fieldError.getField();
            String message = fieldError.getDefaultMessage();
            errMap.put(field,message);
        }
         return Result.build(errMap, ResultCodeEnum.INVAILD_PARAM);
    }

    /**
     * 处理所有controller出现的其他异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        log.error("系统异常：{}",e);
        Result<Object> fail = Result.fail();
        fail.setMessage(e.getMessage());
        return fail;
    }

}